package cn.dakaqi.apps.group.admin.aspect;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Arrays;
import java.util.Calendar;
import java.util.ResourceBundle;

/**
 * Created by chunyang on 2016/5/22.
 */
@Aspect
@Component
@Slf4j
public class WebLogAspect
{


    @Pointcut("execution(public * cn.dakaqi.apps.group.admin.controller..*.*(..))")
    public void webLog(){}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(null == attributes)
            return;

        HttpServletRequest request = attributes.getRequest();
        String IP = getIpAddr(request);
        MDC.put("ip", IP);
        MDC.put("param", Arrays.toString(joinPoint.getArgs()));
        MDC.put("URL", request.getRequestURL().toString());

        // 记录下请求内容
//        log.info("URL : " + request.getRequestURL().toString());
//        log.info("HTTP_METHOD : " + request.getMethod());
//        log.info("IP : " + IP);
//        log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
//        log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));

        log.info(IP + " " + request.getMethod() + " " + request.getRequestURL().toString());
        log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));

//        StringBuffer sb = new StringBuffer();
//        sb.append("URL : " + request.getRequestURL().toString());
//        sb.append("\r\n");
//        sb.append("HTTP_METHOD : " + request.getMethod());
//        sb.append("\r\n");
//        sb.append("IP : " + IP);
//        sb.append("\r\n");
//        sb.append("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
//        sb.append("\r\n");
//        sb.append("ARGS : " + Arrays.toString(joinPoint.getArgs()));
//        sb.append("\r\n");

        //String appPath = request.getServletContext().getRealPath("/");

        //saveLog(sb.toString());


    }

    public static String getIpAddr(HttpServletRequest request)
    {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getRemoteAddr();
        }
        //log.info("当前访问者IP:" + ip);
        String[] ips = ip.split(",");
        if(ips.length>1)
            return ips[0];
        return ip;
    }
    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {

        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(null == attributes)
            return;

        StringBuffer sb = new StringBuffer();

        // 处理完请求，返回内容
        if(null != ret)
        {
            log.info("RESPONSE:" + JSON.parse(JSON.toJSONString(ret)));
            sb.append("RESPONSE:" + JSON.parse(JSON.toJSONString(ret)));
            sb.append("\r\n");
        }
        else
        {
            log.info("RESPONSE : " + ret);
            sb.append("RESPONSE : " + ret);
            sb.append("\r\n");
        }

        //saveLog(sb.toString());

    }

    public static void saveLog(String content )
    {
        ResourceBundle bundle = ResourceBundle.getBundle("parameter");
        String dir = bundle.getString("adminLog");
        try
        {
            File path = new File(dir);
            if ( !path.exists() )
            {
                path.mkdir();
            }
            File LogDir = new File(path + "/" + (Calendar.getInstance().get(Calendar.MONTH) + 1));
            if ( !LogDir.exists() )
            {
                LogDir.mkdir();
            }
            File file = new File(LogDir + "/" + Calendar.getInstance().get(Calendar.DAY_OF_MONTH) + ".log");
            if ( !file.exists() )
            {
                file.createNewFile();
            }
            BufferedWriter br = new BufferedWriter(new FileWriter(file, true));
            br.write(content);
            br.newLine();
            br.flush();
            br.close();
            File LogDirOld = new File(
                    path
                            + "/"
                            + (Calendar.getInstance().get(Calendar.MONTH) - 2 > 0 ? (Calendar
                            .getInstance().get(Calendar.MONTH) - 2)
                            : Calendar.getInstance()
                            .get(Calendar.MONTH) + 10));
            if ( LogDirOld.exists() )
            {
                File[] fileOlds = LogDirOld.listFiles();
                for ( File f : fileOlds )
                {
                    f.delete();
                }
                LogDirOld.delete();
            }
        }
        catch ( Exception e )
        {
            e.printStackTrace();
        }

    }

}